﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MauiApp1
{
    public class PopupAction
    {
        public static async Task<T?> DisplayPopup<T>(BasePopupPage page) where T : class
        {
            try
            {                
                await Shell.Current.Navigation.PushModalAsync(page);
                return (T)await page.returnResultTask.Task;
            }
            catch (Exception ex)
            {
                return default(T?);
            }
        }

        public static async Task<string> DisplayPopup(BasePopupPage page)
        {
            try
            {
                await Shell.Current.Navigation.PushModalAsync(page);
                return (string)await page.returnResultTask.Task;
            }
            catch (Exception ex)
            {
                return "";
            }

        }

        public static async Task ClosePopup(object? returnValue = null)
        {
            if (Shell.Current.Navigation.ModalStack.Count > 0)
            {
                try
                {
                    if (returnValue != null)
                    {
                        var currentPage = (BasePopupPage?)Shell.Current.Navigation.ModalStack.LastOrDefault();
                        currentPage?.returnResultTask.TrySetResult(returnValue);
                    }
                }
                catch (Exception ex)
                {

                }
                finally
                {
                    await Shell.Current.Navigation.PopModalAsync();
                }
            }
        }

    }
}
